using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Net;

namespace Y360ToWordpress
{
    public partial class Form1 : Form
    {
        private string _tags = "";
        private entries.entriesDataTable entrydt = new entries.entriesDataTable();

        public Form1()
        {
            InitializeComponent();
        }

        private void setupConnection()
        {
            if (checkBox1.Checked)
            {
                WebProxy wp = new WebProxy(txtProxy.Text, Convert.ToInt32(txtPort.Text));

                if (checkBox2.Checked)
                    wp.Credentials = new NetworkCredential(txtUsername.Text, txtPassword.Text, txtDomain.Text);

                WebRequest.DefaultWebProxy = wp;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            entrydt.Clear();
            setupConnection();

            string entryurl = textBox1.Text;

            //DataSet ds = new DataSet();
            //ds.ReadXml(blogurl);

            StringBuilder main = new StringBuilder("");
            StringBuilder entries = new StringBuilder("");
            StringBuilder tags = new StringBuilder("");

            int intryid = 0;

            while (entryurl != "") 
            {
                string tempentryurl = entryurl.Replace("p=", "|");
                string[] _blogurl = tempentryurl.Split(Convert.ToChar("|"));
                string blogurl = _blogurl[0];
                string postid = _blogurl[1];

                saveHTMLLocal(entryurl, "temp");

                StringBuilder entry = new StringBuilder("");

                scapeEntryTagComments(postid, out entry, ref entryurl);

                entries.Append(entry.ToString());

                intryid++;
            }

            tags = buildTagMain();
            main = buildExportFile(tags, entries);

            TextWriter fileWriter = new StreamWriter("final.xml");
            fileWriter.WriteLine(main.ToString());
            fileWriter.Close();

            dataGridView1.DataSource = entrydt;
            MessageBox.Show("Task Complete!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void saveHTMLLocal(string url, string filename)
        {
            WebRequest webRequest = WebRequest.Create(url);

            WebResponse wr = webRequest.GetResponse();
            StreamReader webStream = new StreamReader(wr.GetResponseStream());

            TextWriter fileWriter = new StreamWriter(filename + ".htm");
            fileWriter.WriteLine(webStream.ReadToEnd());
            fileWriter.Close();
            webStream.Close();
        }

        private void scapeEntryTagComments(string postid, out StringBuilder postentry, ref string previousurl)
        {
            HtmlAgilityPack.HtmlDocument hdoc = new HtmlAgilityPack.HtmlDocument();
            hdoc.Load("temp.htm");  

            StringBuilder posttags = new StringBuilder("");
            StringBuilder postcomments = new StringBuilder("");

            postentry = new StringBuilder("");

            // entry
            HtmlAgilityPack.HtmlNode entry = hdoc.DocumentNode.SelectSingleNode("//div[@id='ymgl-blog']");

            if (entry != null)
            {
                string entrytitle   = entry.SelectSingleNode("//dt[@class='post-head']").InnerText;
                string entrycontent = entry.SelectSingleNode("//div[@class='content-wrapper']").InnerHtml;
                string entrydate    = "";

                entries.entriesRow entryrow = entrydt.NewentriesRow();
                entryrow.url = previousurl;
                
                //entries.entriesRow entryrow = entries1.Tables[0].Newentnew entries.entriesRow();// = enNewRow();

                // get previous entry url
                HtmlAgilityPack.HtmlNodeCollection ps = entry.SelectNodes("//div[@class='foot']/p");

                foreach (HtmlAgilityPack.HtmlNode p in ps)
                {
                    if (!p.HasAttributes)
                    {
                        entrydate = p.InnerText.Trim();
                    }
                    else
                    {
                        if (p.Attributes["class"].Value == "nav")
                        {
                            foreach (HtmlAgilityPack.HtmlNode nav in p.ChildNodes)
                            {
                                if (nav.Name.ToLower() == "span")
                                {
                                    if (nav.InnerText.IndexOf("Previous Post:") > -1)
                                        previousurl = nav.SelectSingleNode("a").Attributes["href"].Value;
                                    else
                                        previousurl = "";
                                }
                            }
                        }
                    }
                }

                //previousurl = "";

                // tag
                HtmlAgilityPack.HtmlNode tag = hdoc.DocumentNode.SelectSingleNode("//span[@id='tag-container-" + postid + "']");

                if (tag != null)
                {
                    string tags = tag.InnerText;
                    posttags = buildTagEntry(tags.Split(Convert.ToChar(","))); 
                }

                // comment
                HtmlAgilityPack.HtmlNode node = hdoc.DocumentNode.SelectSingleNode("//div[@id='comments']");

                if (node != null)
                {
                    HtmlAgilityPack.HtmlNodeCollection comments = node.SelectNodes("div");

                    foreach (HtmlAgilityPack.HtmlNode com in comments)
                    {
                        if (com.Attributes["class"].Value != "head")
                        {
                            HtmlAgilityPack.HtmlNode img = com.SelectSingleNode("div[@class='user-card ']/ul[@class='vitals']//a");
                            HtmlAgilityPack.HtmlNode cmt = com.SelectSingleNode("div[@class='wrapper']/p[@class='comment']");
                            HtmlAgilityPack.HtmlNode dte = com.SelectSingleNode("div[@class='wrapper']/p[@class='datestamp']");

                            string commentauther = "";
                            try { commentauther = img.Attributes["title"].Value; }
                            catch { commentauther = "unknown"; }
                            
                            string comment = cmt.InnerHtml;
                            string commentdate = dte.InnerText;

                            postcomments.Append(buildComment(0, commentauther, commentdate, comment));

                        }
                    }
                }

                postentry = buildEntry(Convert.ToInt32(postid), entrytitle, entrydate, entrycontent, posttags, postcomments);

                entryrow.title = entrytitle;
                entryrow.pubdate = entrydate;

                entrydt.AddentriesRow(entryrow);
            }

            hdoc = null;
        }

        private string convertToFriendlyURL(string title)
        {
            string titleurlfriendly = title;

            titleurlfriendly = titleurlfriendly.Replace("/", "");
            titleurlfriendly = titleurlfriendly.Replace("?", "");
            titleurlfriendly = titleurlfriendly.Replace("&", "");
            titleurlfriendly = titleurlfriendly.Replace("=", "");
            titleurlfriendly = titleurlfriendly.Replace("\\", "");
            titleurlfriendly = titleurlfriendly.Replace("<", "");
            titleurlfriendly = titleurlfriendly.Replace(">", "");
            titleurlfriendly = titleurlfriendly.Replace("*", "");
            titleurlfriendly = titleurlfriendly.Replace(":", "");
            titleurlfriendly = titleurlfriendly.Replace(" ", "-");

            return titleurlfriendly.ToLower();

        }

        private StringBuilder buildEntry(int entryid, string title, string pubdate, string content, StringBuilder tags, StringBuilder comments)
        {
            StringBuilder s = new StringBuilder("");

            string titleurlfriendly = convertToFriendlyURL(title);

            string wpusername = "admin";
            DateTime post_date_gmt;//"2008-06-14 13:08:39";
            DateTime pub_date = cleanCommentDate(pubdate, out post_date_gmt);
            DateTime post_date = pub_date;


            s.Append("\n<item>");
            s.Append("\n<title>" + title + "</title>");
            s.Append("\n<link>http://yourwordpressblogtitle.wordpress.com/2008/06/14/" + titleurlfriendly + "/</link>");
            s.Append("\n<pubDate>" + pub_date.ToString("yyyy-MM-dd HH:mm:ss") + "</pubDate>");
            s.Append("\n<dc:creator><![CDATA[" + wpusername + "]]></dc:creator>");
            s.Append("\n");
            s.Append("\n		<category><![CDATA[Uncategorized]]></category>");
            s.Append("\n");
            s.Append("\n		<category domain=\"category\" nicename=\"uncategorized\"><![CDATA[Uncategorized]]></category>");
            s.Append("\n");

            // entry tag
            s.Append(tags.ToString());

            s.Append("\n<guid isPermaLink=\"false\">http://yourwordpressblogtitle.wordpress.com/?p=" + entryid.ToString() + "</guid>");
            s.Append("\n<description></description>");
            s.Append("\n<content:encoded><![CDATA[" + content.Replace("â€¦", "...").Replace("â€œ", "\"").Replace("â€", "\"").Replace("â€™", "'") + "]]></content:encoded>");
            s.Append("\n<excerpt:encoded><![CDATA[]]></excerpt:encoded>");
            s.Append("\n<wp:post_id>" + entryid.ToString() + "</wp:post_id>");
            s.Append("\n<wp:post_date>" + post_date.ToString("yyyy-MM-dd HH:mm:ss") + "</wp:post_date>");
            s.Append("\n<wp:post_date_gmt>" + post_date_gmt.ToString("yyyy-MM-dd HH:mm:ss") + "</wp:post_date_gmt>");
            s.Append("\n<wp:comment_status>open</wp:comment_status>");
            s.Append("\n<wp:ping_status>open</wp:ping_status>");
            s.Append("\n<wp:post_name>" + titleurlfriendly + "</wp:post_name>");
            s.Append("\n<wp:status>publish</wp:status>");
            s.Append("\n<wp:post_parent>0</wp:post_parent>");
            s.Append("\n<wp:menu_order>0</wp:menu_order>");
            s.Append("\n<wp:post_type>post</wp:post_type>");
            s.Append("\n<wp:post_password></wp:post_password>");
            s.Append("\n<wp:postmeta>");
            s.Append("\n<wp:meta_key>_edit_lock</wp:meta_key>");
            s.Append("\n<wp:meta_value>0123456789</wp:meta_value>");
            s.Append("\n</wp:postmeta>");
            s.Append("\n<wp:postmeta>");
            s.Append("\n<wp:meta_key>_edit_last</wp:meta_key>");
            s.Append("\n<wp:meta_value>012345</wp:meta_value>");
            s.Append("\n</wp:postmeta>");

            // comment
            s.Append(comments.ToString());

            s.Append("\n	</item>");

            return s;
        }

        private StringBuilder buildTagEntry(string[] tag)
        {
            StringBuilder s = new StringBuilder("");

            for (int i = 0; i < tag.Length; i++)
            {
                if (tag[i].Trim() != "")
                {
                    s.Append("\n		<category domain=\"tag\"><![CDATA[" + tag[i] + "]]></category>");
                    s.Append("\n");
                    s.Append("\n		<category domain=\"tag\" nicename=\"" + tag[i] + "\"><![CDATA[" + tag[i] + "]]></category>");
                    s.Append("\n");

                    if (_tags.IndexOf(tag[i]) < 0)
                    {
                        _tags += tag[i] + ",";
                    }
                }

            }

            return s;
        }

        private StringBuilder buildTagMain()
        {
            StringBuilder s = new StringBuilder("");

            string[] tags = _tags.Split(Convert.ToChar(","));

            for (int i = 0; i < tags.Length; i++)
            {
                if (tags[i].Trim() != "")
                {                    
                    s.Append("\n	<wp:tag><wp:tag_slug>" + tags[i] + "</wp:tag_slug><wp:tag_name><![CDATA[" + tags[i] + "]]></wp:tag_name></wp:tag>");
                }
            }

            return s;
        }

        private StringBuilder buildComment(int commentid, string author, string datestamp, string comment)
        { 
            StringBuilder s = new StringBuilder("");

            DateTime commentgmtdate;
            DateTime commentdate = cleanCommentDate(datestamp, out commentgmtdate);

            s.Append("\n<wp:comment>");
            s.Append("\n<wp:comment_id>" + commentid.ToString() + "</wp:comment_id>");
            s.Append("\n<wp:comment_author><![CDATA[" + author + "]]></wp:comment_author>");
            s.Append("\n<wp:comment_author_email>me@yahoo.com</wp:comment_author_email>");
            s.Append("\n<wp:comment_author_url></wp:comment_author_url>");
            s.Append("\n<wp:comment_author_IP>127.0.0.1</wp:comment_author_IP>");
            s.Append("\n<wp:comment_date>" + commentdate.ToString("yyyy-MM-dd HH:mm:ss") + "</wp:comment_date>");
            s.Append("\n<wp:comment_date_gmt>" + commentgmtdate.ToString("yyyy-MM-dd HH:mm:ss") + "</wp:comment_date_gmt>");
            s.Append("\n<wp:comment_content><![CDATA[" + comment + "]]></wp:comment_content>");
            s.Append("\n<wp:comment_approved>1</wp:comment_approved>");
            s.Append("\n<wp:comment_type></wp:comment_type>");
            s.Append("\n<wp:comment_parent>0</wp:comment_parent>");
            s.Append("\n<wp:comment_user_id>0</wp:comment_user_id>");
            s.Append("\n</wp:comment>");

            return s;
        }

        private StringBuilder buildExportFile(StringBuilder tags, StringBuilder entries)
        {
            StringBuilder s = new StringBuilder("");

            s.Append("\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            s.Append("\n<!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your blog. -->");
            s.Append("\n<!-- It contains information about your blog's posts, comments, and categories. -->");
            s.Append("\n<!-- You may use this file to transfer that content from one site to another. -->");
            s.Append("\n<!-- This file is not intended to serve as a complete backup of your blog. -->");
            s.Append("\n");
            s.Append("\n<!-- To import this information into a WordPress blog follow these steps. -->");
            s.Append("\n<!-- 1. Log into that blog as an administrator. -->");
            s.Append("\n<!-- 2. Go to Manage: Import in the blog's admin panels. -->");
            s.Append("\n<!-- 3. Choose \"WordPress\" from the list. -->");
            s.Append("\n<!-- 4. Upload this file using the form provided on that page. -->");
            s.Append("\n<!-- 5. You will first be asked to map the authors in this export file to users -->");
            s.Append("\n<!--    on the blog.  For each author, you may choose to map to an -->");
            s.Append("\n<!--    existing user on the blog or to create a new user -->");
            s.Append("\n<!-- 6. WordPress will then import each of the posts, comments, and categories -->");
            s.Append("\n<!--    contained in this file into your blog -->");
            s.Append("\n");
            s.Append("\n<!-- generator=\"WordPress/MU\" created=\"2008-06-14 05:15\"-->");
            s.Append("\n<rss version=\"2.0\"");
            s.Append("\n	xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"");
            s.Append("\n	xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"");
            s.Append("\n	xmlns:dc=\"http://purl.org/dc/elements/1.1/\"");
            s.Append("\n	xmlns:wp=\"http://wordpress.org/export/1.0/\"");
            s.Append("\n>");
            s.Append("\n");
            s.Append("\n<channel>");
            s.Append("\n	<title>Your Wordpress Blog Title</title>");
            s.Append("\n	<link>http://yourwordpressblogtitle.wordpress.com</link>");
            s.Append("\n	<description>Your Wordpress Blog Description</description>");
            s.Append("\n	<pubDate>Tue, 1 Jan 2008 05:09:02 +0000</pubDate>");
            s.Append("\n	<generator>http://wordpress.org/?v=MU</generator>");
            s.Append("\n	<language>en</language>");
            s.Append("\n	<wp:wxr_version>1.0</wp:wxr_version>");
            s.Append("\n	<wp:base_site_url>http://wordpress.com/</wp:base_site_url>");
            s.Append("\n	<wp:base_blog_url>http://yourwordpressblogtitle.wordpress.com</wp:base_blog_url>");
            s.Append("\n	<wp:category><wp:category_nicename>uncategorized</wp:category_nicename><wp:category_parent></wp:category_parent><wp:cat_name><![CDATA[Uncategorized]]></wp:cat_name></wp:category>");

            // main tag
            s.Append(tags.ToString());
            
            // entry
            s.Append(entries.ToString());

            s.Append("\n</channel>");
            s.Append("\n</rss>");

            return s;
        }

        private DateTime cleanCommentDate(string ydate, out DateTime gmtdate)
        {
            ydate = ydate.Replace("- ", "");

            double gmtplus = 0;

            if (ydate.IndexOf("(NST)") > 0)
            {
                gmtplus = 3.5;
                ydate = ydate.Replace("(NST)", "");
            }
            else if (ydate.IndexOf("(NDT)") > 0)
            {
                gmtplus = 2.5;
                ydate = ydate.Replace("(NDT)", "");
            }
            else if (ydate.IndexOf("(AST)") > 0)
            {
                gmtplus = 4;
                ydate = ydate.Replace("(AST)", "");
            }
            else if (ydate.IndexOf("(ADT)") > 0)
            {
                gmtplus = 3;
                ydate = ydate.Replace("(ADT)", "");
            }
            else if (ydate.IndexOf("(EST)") > 0)
            {
                gmtplus = 5;
                ydate = ydate.Replace("(EST)", "");
            }
            else if (ydate.IndexOf("(EDT)") > 0)
            {
                gmtplus = 4;
                ydate = ydate.Replace("(EDT)", "");
            }
            else if (ydate.IndexOf("(CST)") > 0)
            {
                gmtplus = 6;
                ydate = ydate.Replace("(CST)", "");
            }
            else if (ydate.IndexOf("(CDT)") > 0)
            {
                gmtplus = 5;
                ydate = ydate.Replace("(CDT)", "");
            }
            else if (ydate.IndexOf("(MST)") > 0)
            {
                gmtplus = 7;
                ydate = ydate.Replace("(MST)", "");
            }
            else if (ydate.IndexOf("(MDT)") > 0)
            {
                gmtplus = 6;
                ydate = ydate.Replace("(MDT)", "");
            }
            else if (ydate.IndexOf("(PST)") > 0)
            {
                gmtplus = 8;
                ydate = ydate.Replace("(PST)", "");
            }
            else if (ydate.IndexOf("(PDT)") > 0)
            {
                gmtplus = 7;
                ydate = ydate.Replace("(PDT)", "");
            }
            else if (ydate.IndexOf("(AKST)") > 0)
            {
                gmtplus = 9;
                ydate = ydate.Replace("(AKST)", "");
            }
            else if (ydate.IndexOf("(AKDT)") > 0)
            {
                gmtplus = 8;
                ydate = ydate.Replace("(AKDT)", "");
            }
            else if (ydate.IndexOf("(HAST)") > 0)
            {
                gmtplus = 10;
                ydate = ydate.Replace("(HAST)", "");
            }
            else if (ydate.IndexOf("(HADT)") > 0)
            {
                gmtplus = 9;
                ydate = ydate.Replace("(HADT)", "");
            }
            else
            {
                gmtplus = 0;
                string[] _ydate = ydate.Split(Convert.ToChar("("));
                ydate = _ydate[0];
            }

            ydate = ydate.Replace("Sunday", "");
            ydate = ydate.Replace("Monday", "");
            ydate = ydate.Replace("Tuesday", "");
            ydate = ydate.Replace("Wednesday", "");
            ydate = ydate.Replace("Thursday", "");
            ydate = ydate.Replace("Friday", "");
            ydate = ydate.Replace("Saturday", "");

            DateTime newdate = Convert.ToDateTime(ydate);
            gmtdate = newdate.AddHours(gmtplus);

            return newdate;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            txtProxy.Enabled = checkBox1.Checked;
            txtPort.Enabled = checkBox1.Checked;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            txtUsername.Enabled = checkBox2.Checked;
            txtPassword.Enabled = checkBox2.Checked;
            txtDomain.Enabled = checkBox2.Checked;
        }
    }
}